#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import os.path
import platform

from common.common import read_platform_result_file
from common.file_common import delete_path, create_dir_recursive
from common.util.exec_utils import exec_mkdir_cmd
from oracle import logger
from oracle.common.constants import Platform, PluginPathConstant


def get_omf_dest(pfile_path: str) -> str:
    pfile_name_lines = read_platform_result_file(pfile_path).splitlines()
    for line in pfile_name_lines:
        if "DB_CREATE_FILE_DEST=" in line or "db_create_file_dest=" in line:
            audit_file_dest_line = line.strip()
            omf_dest = audit_file_dest_line.split("#")[0].split("=")[1].replace("'", "")
            return omf_dest
    return ""


def build_omf_recovery_file_dest(db_name: str, db_install_user: str, recover_dst: str):
    db_name = db_name.upper().replace("'", "").strip()
    control_file_dir = os.path.join(recover_dst, db_name, "controlfile")
    datafile_dir = os.path.join(recover_dst, db_name, "datafile")
    onlinelog_dir = os.path.join(recover_dst, db_name, "onlinelog")
    tempfile_dir = os.path.join(recover_dst, db_name, "tempfile")
    file_list = [control_file_dir, datafile_dir, onlinelog_dir, tempfile_dir]
    if platform.system().lower() == Platform.WINDOWS:
        for file_path in file_list:
            create_dir_recursive(file_path)
    else:
        for file_path in file_list:
            exec_mkdir_cmd(file_path, db_install_user, is_check_white_list=False)
    return {
        "control_files": os.path.join(control_file_dir, "controlfile.ctl"),
        "db_create_file_dest": recover_dst,
    }


def clean_aix_restore_ln_path():
    logger.info("start to clean aix restore ln path")
    if platform.system().lower() == Platform.AIX:
        logger.info("start to clean aix restore ln path")
        delete_path(PluginPathConstant.AIX_RESTORE_DATA.value)
        delete_path(PluginPathConstant.AIX_RESTORE_LOG.value)
